package com.yanqu.road.server.manger.activity;

import com.yanqu.road.entity.activity.ActivityInfo;
import com.yanqu.road.entity.activity.UnionActivityTaskData;
import com.yanqu.road.entity.activity.UserActivityConditionData;
import com.yanqu.road.entity.union.activitygroup.UnionActivityGroupUnion;
import com.yanqu.road.entity.union.activitygroup.UnionActivityGroupUser;
import com.yanqu.road.entity.union.cross.CrossUnionMember;
import com.yanqu.road.logic.helper.UnionActivityGroupHelper;
import com.yanqu.road.logic.helper.UnionActivityTaskConditionHelper;
import com.yanqu.road.pb.union.cross.CrossUnionActivityTaskProto;
import com.yanqu.road.server.GameServer;
import com.yanqu.road.server.TempMgr;
import com.yanqu.road.server.gameplayer.GamePlayer;
import com.yanqu.road.server.gameplayer.module.activity.ActivityModule;
import com.yanqu.road.server.logic.activity.BaseActivityData;
import com.yanqu.road.server.manger.player.GamePlayerMgr;
import com.yanqu.road.server.manger.union.CrossUnionMgr;
import com.yanqu.road.server.manger.union.GameUnionActivityGroupMgr;
import com.yanqu.road.server.protocol.CrossProtocol;
import com.yanqu.road.utils.string.StringUtils;

import java.math.BigInteger;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

public class UnionActivityTaskMgr extends TempMgr {

    // Map<活动ID，商会ID，conditionId，数据>
    private static Map<Integer, Map<String, Map<Integer, UnionActivityTaskData>>> activityUnionTaskMap = new ConcurrentHashMap<>();


    /**
     * 添加要上传的数据
     */
    public static void addUploadData(int activityId, String unionUid, int conditionId, long addValue) {
        synchronized (activityUnionTaskMap) {
            activityUnionTaskMap.putIfAbsent(activityId, new ConcurrentHashMap<>());
            Map<String, Map<Integer, UnionActivityTaskData>> mapMap = activityUnionTaskMap.get(activityId);
            mapMap.putIfAbsent(unionUid, new ConcurrentHashMap<>());
            Map<Integer, UnionActivityTaskData> map = mapMap.get(unionUid);
            if (!map.containsKey(conditionId)) {
                map.put(conditionId, new UnionActivityTaskData(activityId, unionUid, conditionId, 0L));
            }
            UnionActivityTaskData data = map.get(conditionId);
            data.setValue(data.getValue() + addValue);
        }
    }

    /**
     * 上传数据
     */
    public static void uploadData() {
        Map<Integer, Map<String, Map<Integer, UnionActivityTaskData>>> map;
        synchronized (activityUnionTaskMap) {
            map = new ConcurrentHashMap<>(activityUnionTaskMap);
            activityUnionTaskMap.clear();
        }

        // 按活动同步到跨服
        for (Map.Entry<Integer, Map<String, Map<Integer, UnionActivityTaskData>>> entry : map.entrySet()) {
            Integer activityId = entry.getKey();

            Map<Integer, CrossUnionActivityTaskProto.SyncUnionActivityTaskMsg.Builder> groupMap = new HashMap<>();
            for (Map<Integer, UnionActivityTaskData> dataMap : entry.getValue().values()) {
                for (UnionActivityTaskData taskData : dataMap.values()) {

                    int groupId = GameUnionActivityGroupMgr.getGroupId(activityId, taskData.getUnionUid());
                    if (groupId == UnionActivityGroupHelper.NO_GROUP_ID) {
                        continue;
                    }

                    CrossUnionActivityTaskProto.SyncUnionActivityTaskMsg.Builder builder = groupMap.get(groupId);
                    if (builder == null) {
                        builder = CrossUnionActivityTaskProto.SyncUnionActivityTaskMsg.newBuilder();
                        builder.setActivityId(activityId);
                        groupMap.put(groupId, builder);
                    }

                    CrossUnionActivityTaskProto.UnionActivityTaskMsg.Builder tmp = CrossUnionActivityTaskProto.UnionActivityTaskMsg.newBuilder();
                    tmp.setUnionUid(taskData.getUnionUid());
                    tmp.setConditionId(taskData.getConditionId());
                    tmp.setValue(taskData.getValue());
                    builder.addTaskList(tmp);
                }
            }

            for (Map.Entry<Integer, CrossUnionActivityTaskProto.SyncUnionActivityTaskMsg.Builder> entry2 : groupMap.entrySet()) {
                int groupId = entry2.getKey();
                GamePlayerMgr.sendUnionActivityGroupPacket(CrossProtocol.C2_UNION_ACTIVITY_TASK_UPLOAD_DATA, entry2.getValue(), 0, activityId, groupId);
            }
        }
    }

    /**
     * 更新全部在线玩家数据
     */
    public static void updateOnlinePlayerData(CrossUnionActivityTaskProto.SyncUnionActivityTaskMsg msg) {
        int activityId = msg.getActivityId();
        long serverId = GameServer.getInstance().getServerId();
        for (CrossUnionActivityTaskProto.UnionActivityTaskMsg taskMsg : msg.getTaskListList()) {
            String unionUid = taskMsg.getUnionUid();
            List<Long> memberIds = GameUnionActivityGroupMgr.getActivityUnionMemberIds(activityId, unionUid);
            for (Long memberId : memberIds) {
                GamePlayer onlinePlayer = GamePlayerMgr.getOnlinePlayer(memberId);
                if (onlinePlayer != null) {
                    ActivityModule activityModule = onlinePlayer.getModule(ActivityModule.class);
                    BaseActivityData baseActivityData = activityModule.getBaseActivityData(activityId);
                    if (baseActivityData != null) {
                        UserActivityConditionData conditionData = baseActivityData.getUserActivityConditionData(taskMsg.getConditionId());
                        if (!conditionData.isGetReward()) {
                            conditionData.setValue(BigInteger.valueOf(taskMsg.getValue()));
                            activityModule.onActivityDataChanged(baseActivityData);
                        }
                    }
                }
            }
        }
    }

    /**
     * 更新单个玩家数据
     */
    public static void updateOnlinePlayerData(GamePlayer player, CrossUnionActivityTaskProto.SyncUnionActivityTaskMsg msg) {
        String unionUid = player.getUserInfo().getUnionUid();
        if ("".equals(unionUid)) {
            return;
        }

        int activityId = msg.getActivityId();
        ActivityModule activityModule = player.getModule(ActivityModule.class);
        BaseActivityData baseActivityData = activityModule.getBaseActivityData(activityId);
        for (CrossUnionActivityTaskProto.UnionActivityTaskMsg taskMsg : msg.getTaskListList()) {
            unionUid = GameUnionActivityGroupMgr.getActivityUnionUid(baseActivityData.getActivityInfo(), player);
            if (taskMsg.getUnionUid().equals(unionUid)) {
                UserActivityConditionData conditionData = baseActivityData.getUserActivityConditionData(taskMsg.getConditionId());
                if (!conditionData.isGetReward()) {
                    conditionData.setValue(BigInteger.valueOf(taskMsg.getValue()));
                    activityModule.onActivityDataChanged(baseActivityData);
                }
            }
        }
    }


    // ============================================================================


    public static void quitUnion(long userId) {
        GamePlayer onlinePlayer = GamePlayerMgr.getOnlinePlayer(userId);
        if (onlinePlayer != null) {
            for (ActivityInfo activityInfo : NormalActivityMgr.getShowTimeActivityInfoList()) {
                String unionUid = GameUnionActivityGroupMgr.getActivityUnionUid(activityInfo, onlinePlayer);
                if (!StringUtils.isNullOrEmpty(unionUid)) {//锁名单后,离会了还是有商会的
                    continue;
                }
                if (UnionActivityTaskConditionHelper.isActivityTypeContainsUnionCondition(activityInfo.getType())) {
                    ActivityModule activityModule = onlinePlayer.getModule(ActivityModule.class);
                    BaseActivityData baseActivityData = activityModule.getBaseActivityData(activityInfo.getActivityId());
                    for (UserActivityConditionData conditionData : baseActivityData.getUserActivityConditionDataList()) {
                        if (UnionActivityTaskConditionHelper.isUnionActivityConditionType(conditionData.getType())) {
                            if (!conditionData.isGetReward()) {
                                conditionData.setValue(BigInteger.ZERO);
                                activityModule.onActivityDataChanged(baseActivityData);
                            }
                        }
                    }
                }
            }
        }
    }

    public static void joinUnion(long userId) {
        loginRefreshValue(userId);
    }

    /*
    public static void deleteUnion(String unionUid) {
        long serverId = GameServer.getInstance().getServerId();
        Map<Long, CrossUnionMember> memberMap = CrossUnionMgr.getUnionMemberMap(unionUid);
        if (memberMap != null) {
            for (CrossUnionMember unionMember : memberMap.values()) {
                if (unionMember.getServerId() == serverId) {
                    quitUnion(unionMember.getUserId());
                }
            }
        }
    }
    */

    public static void loginRefreshValue(long userId) {
        GamePlayer onlinePlayer = GamePlayerMgr.getOnlinePlayer(userId);
        if (onlinePlayer != null) {

            String unionUid = onlinePlayer.getUserInfo().getUnionUid();

//            // 登录时发现被踢了，好惨
//            if ("".equals(unionUid)) {
//                quitUnion(userId);
//                return;
//            }


            // 没被踢就找跨服要数据
            for (ActivityInfo activityInfo : NormalActivityMgr.getShowTimeActivityInfoList()) {
                if (UnionActivityTaskConditionHelper.isActivityTypeContainsUnionCondition(activityInfo.getType())) {
                    CrossUnionActivityTaskProto.GetUnionActivityTaskReqMsg.Builder builder = CrossUnionActivityTaskProto.GetUnionActivityTaskReqMsg.newBuilder();
                    unionUid = GameUnionActivityGroupMgr.getActivityUnionUid(activityInfo, onlinePlayer);
                    if (StringUtils.isNullOrEmpty(unionUid)) {//锁名单后用这个判断
                        quitUnion(userId);
                        continue;
                    }
                    builder.setActivityId(activityInfo.getActivityId());
                    builder.setUnionUid(unionUid);
                    onlinePlayer.sendUnionActivityGroupPacket(CrossProtocol.C2_UNION_ACTIVITY_TASK_GET_DATA, builder, activityInfo.getActivityId());
                }
            }
        }
    }


    // ============================================================================


    @Override
    public boolean init() throws Exception {
        return reload();
    }

    @Override
    public boolean reloadConfig() throws Exception {
        return true;
    }

    @Override
    public boolean reloadData() throws Exception {
        return true;
    }

    @Override
    public boolean stop() {
        return true;
    }
}
